import { Component, OnInit, Injector } from '@angular/core';
import { ListBase } from 'app/modules/base/list-base';
import { map } from 'rxjs/operators';
import { ComputerStatus, ComputerService, ComputerInfo } from '../../services/computer.service';
import { SoftwareService } from 'app/modules/software/services/software.service';
import { MySelection } from 'app/modules/base/selection';

@Component({
  selector: 'm-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
})
export class ListComponent extends ListBase implements OnInit {
  constructor(
    private injector: Injector,
    private pcManager: ComputerService,
    private softwareService: SoftwareService,
  ) {
    super(injector);
  }
  Status = ComputerStatus;
  Sortable = [
    'id',
    'name',
    'need_upgrade',
    'status',
    'update_admin_username',
    'updated_at',
    'created_at',
  ];

  result$ = this.route.data.pipe(map((data) => data.list));

  selection = new MySelection<ComputerInfo>('id');
  ngOnInit() {}
  async status(status: ComputerStatus, ...cid: number[]) {
    if (
      (await this.sweet.confirm(`确定要${status === ComputerStatus.Enable ? '启用' : '停用'}吗？`))
        .dismiss
    ) {
      return;
    }
    if (!cid.length) {
      cid = [...this.selection.keys()];
    }
    await this.pcManager.batch('status', status, cid);
    this.reload();
  }

  async enable(pid: number[]) {
    await this.pcManager.batch('status', this.Status.Enable, pid);
    this.reload();
  }
  async disable(pid: number[]) {
    await this.pcManager.batch('status', this.Status.Disable, pid);
    this.reload();
  }

  async upgrade(cid: number[]) {
    if (!cid) {
      cid = [...this.selection.keys()];
    }
    await this.pcManager.upgrade({ computerIDs: cid });
    this.reload();
  }

  async upgradeSoftware(...cid: number[]) {
    if (!cid.length) {
      cid = [...this.selection.keys()];
    }
    await this.softwareService.upgrade({ computerIDs: cid });
    this.reload();
  }
  async delete(...list: ComputerInfo[]) {
    if (!list.length) {
      list = [...this.selection.selected];
    }
    const result = await this.sweet.confirm(
      `确定要删除[${list.map((pc) => pc.name).join(',')}]吗？`,
    );
    if (result.dismiss) {
      return;
    }
    await this.pcManager.delete(list.map((pc) => pc.id));
    this.reload();
  }

  expolt() {
    let herf = location.search;
    let url;
    if (herf.indexOf('?') != -1) {
      url = '/api/admin/pc?' + herf.split('?')[1] + '&&exportcsv=1';
    } else {
      url = '/api/admin/pc?exportcsv=1';
    }
    window.open(url, '_self');
  }
}
